package org.lzy.shop.fragment

import androidx.recyclerview.widget.LinearLayoutManager
import org.lzy.shop.adapter.ClassifyAdapter
import org.lzy.shop.adapter.ClassifyGroupAdapter
import org.lzy.shop.base.BaseMvvmFragment
import org.lzy.shop.databinding.FragClassifyBinding
import org.lzy.shop.response.ClassifyGroup
import org.lzy.shop.response.HomeClassifyResponse
import org.lzy.shop.response.HomeClassifyTree
import org.lzy.shop.viewmodel.ClassifyModel

/**
 * 分类fragment
 */
class ClassifyFragment: BaseMvvmFragment<FragClassifyBinding, ClassifyModel>(FragClassifyBinding::inflate) {
    private var currentPosition = 0
    private var categoryTrees: List<HomeClassifyTree> = emptyList()
    //左侧分组适配器
    private val mClassifyAdapter: ClassifyAdapter by lazy { ClassifyAdapter() }

    //右侧分组适配器
    private val mClassifyGroupAdapter: ClassifyGroupAdapter by lazy { ClassifyGroupAdapter() }



    override fun initView() {
        binding.frgClassfiyLvLeft.apply {
            layoutManager= LinearLayoutManager(requireActivity(), LinearLayoutManager.VERTICAL, false)
            adapter=mClassifyAdapter
        }

        binding.frgClassfiyLvRight.apply {
            layoutManager = LinearLayoutManager(requireActivity(), LinearLayoutManager.VERTICAL, false)
            adapter = mClassifyGroupAdapter
        }

        mClassifyAdapter.setOnItemClickListener { adapter, _, position ->
            val response = adapter.getItem(position) as? HomeClassifyTree
            response?.let {
                currentPosition = position
                mClassifyAdapter.setPosition(position)
                mClassifyAdapter.notifyDataSetChanged()

                // 直接使用当前分类的ID作为父ID查询子分类
                updateRightContent(response.id, categoryTrees)

            }
        }

    }



    override fun requestData() {
        //获取左侧的分类
        mViewModel.getHomeClassify()

    }



    override fun initData() {
        mViewModel.classifyLiveData.observeWithLifecycle(viewLifecycleOwner) { classifyResponses ->
            classifyResponses?.let {
                val treeData = convertToTree(it)
                mClassifyAdapter.submitList(treeData)

                // 默认显示第一个分类的子分类
                if (treeData.isNotEmpty()) {
                    val firstCategory = treeData[0]
                    updateRightContent(firstCategory.id, categoryTrees)
                }
            }
        }

    }

    private fun convertToTree(categories: List<HomeClassifyResponse>): List<HomeClassifyTree> {
        // 按sortNum排序的列表
        val sortedList = categories.sortedBy { it.sortNum }

        // 将Category转换为CategoryTree
        categoryTrees = sortedList.map { HomeClassifyTree.fromCategory(it) }

        // 构建子分类映射，key是父ID，value是子分类列表
        val childrenMap = buildChildrenMap(categoryTrees)

        // 构建完整的树结构
        return categoryTrees
            .filter { it.parentId == null || it.parentId == 0 }
            .map { buildCategoryTree(it, childrenMap) }
    }

    /**
     * 构建子分类映射表
     */
    private fun buildChildrenMap(categories: List<HomeClassifyTree>): Map<Long, List<HomeClassifyTree>> {
        val childrenMap = mutableMapOf<Long, MutableList<HomeClassifyTree>>()

        categories.forEach { category ->
            category.parentId?.let {
                val parentLongId = it.toLong()
                if (!childrenMap.containsKey(parentLongId)) {
                    childrenMap[parentLongId] = mutableListOf()
                }
                childrenMap[parentLongId]?.add(category)
            }
        }

        return childrenMap
    }

    /**
     * 递归构建分类树结构
     */
    private fun buildCategoryTree(categoryTree: HomeClassifyTree, childrenMap: Map<Long, List<HomeClassifyTree>>): HomeClassifyTree {
        val children = childrenMap[categoryTree.id] ?: emptyList()

        // 如果没有子分类，直接返回
        if (children.isEmpty()) {
            return categoryTree
        }

        // 递归构建每个子分类的树
        val childrenTree = children.map { child ->
            buildCategoryTree(child, childrenMap)
        }

        // 创建一个新的CategoryTree对象，包含子分类列表
        return categoryTree.copy(children = childrenTree)
    }

    /**
     * 根据父ID获取右侧分类列表
     */
    private fun updateRightContent(parentId: Long, categoryTrees: List<HomeClassifyTree>) {
        // 1. 找到所有一级分类（parentId为null或0的分类）
        val firstLevelCategories = categoryTrees.filter { it.parentId == null || it.parentId == 0 }

        // 2. 为每个一级分类创建分组
        val groups = mutableListOf<ClassifyGroup>()

        firstLevelCategories.forEach { category ->
            // 3. 查找该分类下的所有二级分类
            val subCategories = categoryTrees.filter { it.parentId?.toLong() == category.id }

            // 4. 将该分类和其子分类添加到分组
            if (subCategories.isNotEmpty()) {
                groups.add(ClassifyGroup(category.name, subCategories))
            }
        }

        // 5. 设置适配器数据
        mClassifyGroupAdapter.submitList(groups)
        scrollToSelectedCategory(parentId, groups)
    }

    private fun scrollToSelectedCategory(parentId: Long, groups: List<ClassifyGroup>) {
        // 找到对应分类在分组中的位置
        val position = groups.indexOfFirst { group ->
            // 查找ID为parentId的分类名称
            val selectedCategory = categoryTrees.find {
                it.id == parentId && (it.parentId == null || it.parentId == 0)
            }
            selectedCategory?.name == group.title
        }

        // 如果找到对应位置，则滚动到该位置
        if (position >= 0) {
            binding.frgClassfiyLvRight.post {
                binding.frgClassfiyLvRight.scrollToPosition(position)
            }
        }
    }

    override fun allClick() {

    }


}